
/*
 * Hlpay-Plus aggregate payment system. Copyright
 * (c) 2022-2023 Hlpay Team Copyright has the right of final interpretation.
 */

package com.hlkj.pay.service.token.impl;

import cn.hutool.core.util.RandomUtil;
import com.hlkj.framework.caches.service.RedisTemplateService;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.date.LocalDateTimeUtils;
import com.hlkj.pay.common.constants.TokenRedisConstant;
import com.hlkj.pay.enums.AuthTokenEnum;
import com.hlkj.pay.dto.admin.AdminUserDto;
import com.hlkj.pay.infrastructure.model.token.TokenSecretDO;
import com.hlkj.pay.service.admin.IAdminUserService;
import com.hlkj.pay.vo.common.resp.token.MfaResp;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author HlpayTeam
 * @date 2024/09/27 17:51
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MessageSendService {

    private final RedisTemplateService redisTemplateService;

    private final IAdminUserService userService;

    // private final CommonController messageSendClient;

    @Value("${message.business_code.mfa:AUTH_MFA_CODE}")
    private String businessCode;

    /**
     * authCode
     * 
     * @param userId
     * @param type
     * @param tenantSecretDO
     * @return
     */
    public CommonResult<MfaResp> authCode(Long userId, Integer type, TokenSecretDO tenantSecretDO) {
        AdminUserDto userResp = userService.queryUserDto(userId);
        userResp.setPhone("18327318860");
        String code = RandomUtil.randomNumbers(6);
        String userAuthCodeKey = userAuthCodeKey( userId);
        AuthTokenEnum.AUTH_MFA_TYPE authMfaType = AuthTokenEnum.AUTH_MFA_TYPE.from(type);
        try {
            switch (authMfaType) {
                // case PHONE:
                //     if (!StringUtils.hasText(userResp.getPhone())) {
                //         return CommonResult.error(TenantResultCode.USER_PHONE_NOT_EXIST);
                //     }
                //     SmsSendReq smsSendReq = new SmsSendReq();
                //     smsSendReq.setBusinessCode(businessCode);
                //     smsSendReq.setVerifCode(code);
                //     smsSendReq.setPhone(userResp.getPhone());
                //     smsSendReq.setLanguage(userResp.getLanguage());
                //     messageSendClient.sendSms(smsSendReq);
                //     break;
                // default:
                //     if (!StringUtils.hasText(userResp.getEmail())) {
                //         return CommonResult.error(TenantResultCode.USER_EMAIL_NOT_EXIST);
                //     }
                //     EmailSendReq emailSendReq = new EmailSendReq();
                //     emailSendReq.setBusinessCode(businessCode);
                //     emailSendReq.setVerifCode(code);
                //     emailSendReq.setEmail(userResp.getEmail());
                //     emailSendReq.setLanguage(userResp.getLanguage());
                //     messageSendClient.sendEmail(emailSendReq);
            }
        }
        catch (Exception e) {
            log.error("auth_mfa_code send message fail:{}", e.getMessage(), e);
        }

        String userAuthCodeTimeKey = userAuthCodeTimeKey(userId);
        // 清除之前的key
        redisTemplateService.set(userAuthCodeKey, code, tenantSecretDO.getMfaTokenValidity());
        long authCodeTime = LocalDateTimeUtils.datatimeToTimestamp(LocalDateTime.now());
        redisTemplateService.set(userAuthCodeTimeKey, authCodeTime, TokenRedisConstant.TOKEN_USER_AUTH_CODE_TIME_EXPIRE_TIME);
        log.info("authCode:{}", code);
        MfaResp mfaResp = new MfaResp();
        mfaResp.setAuthCode(code);
        mfaResp.setAuthCodeTime(authCodeTime);
        return CommonResult.success(mfaResp);
    }

    /**
     * checkAuthCode
     * 
     * @param userId
     * @param authCode
     * @param tenantSecretDO
     * @return
     */
    public boolean checkAuthCode(Long userId, String authCode, TokenSecretDO tenantSecretDO) {
        String userAuthCodeKey = userAuthCodeKey(userId);
        Object object = redisTemplateService.get(userAuthCodeKey);
        if (object == null) {
            return false;
        }
        return authCode.equals(object.toString());
    }

    /**
     * userTokenKey
     * 
     * @param tenantId
     * @param userId
     * @return
     */
    String userAuthCodeKey(Long userId) {
        StringBuilder sb = new StringBuilder(TokenRedisConstant.TOKEN_USER_AUTH_CODE);
        sb.append(userId);
        return sb.toString();
    }

    /**
     * userTokenKey
     * 
     * @param tenantId
     * @param userId
     * @return
     */
    String userAuthCodeTimeKey(Long userId) {
        StringBuilder sb = new StringBuilder(TokenRedisConstant.TOKEN_USER_AUTH_CODE_TIME);
        sb.append(userId);
        return sb.toString();
    }

}
